package com.red.star.macalline.sched.service;

import com.red.star.macalline.data.core.base.RedisRunner;
import com.red.star.macalline.data.core.constant.RedisConstant;
import com.red.star.macalline.data.entity.Fans;
import com.red.star.macalline.data.mappers.FansMapper;
import com.red.star.macalline.data.utils.CheckUtil;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @author nofish.yan@gmail.com
 * @date 2018/3/19.
 * 粉丝相关操作服务类
 */
@Service
public class FansService {

    @Resource
    private RedisRunner redisRunner;

    @Resource
    private FansMapper fansMapper;

    /**
     * 根据ID查找粉丝信息
     *
     * @param fansId
     * @return
     */
    public Fans findFansById(Integer fansId) {
        Fans fans = null;
        Jedis jedis = null;
        try {
            jedis = redisRunner.getResource(RedisConstant.REDIS_DB_USER_SESSION);
            Map<String, String> map = jedis.hgetAll("user:" + fansId);
            if (CheckUtil.isEmpty(map)) {
                fans = fansMapper.selectByPrimaryKey(fansId);
                fans.setNickname(URLDecoder.decode(fans.getNickname(), "utf-8"));
                // 存入缓存
                jedis.hset("user:" + fansId, "nickname", fans.getNickname());
                jedis.hset("user:" + fansId, "avatar", fans.getAvatarUrl());
                jedis.hset("user:" + fansId, "type", fans.getType().toString());
                return fans;
            }
            fans = new Fans();
            fans.setId(fansId);
            fans.setNickname(map.get("nickname"));
            fans.setAvatarUrl(map.get("avatar"));
            fans.setType(Integer.parseInt(map.get("type")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                redisRunner.returnResource(jedis);
            }
        }
        return fans;
    }

    /**
     * 查询粉丝是否是导购员
     *
     * @param fansId 粉丝ID
     * @return true 是导购员
     */
    public boolean isEmployee(Integer fansId) {
        Fans fans = findFansById(fansId);
        return (fans != null && fans.getType() == 1) ? true : false;
    }

}
